//
//  XCReconnectManager.swift
//  RXSwiftDemo1
//
//  Created by mac on 2025/3/6.
//

import Foundation
import RxSwift
import CoreBluetooth

class XCReconnectManager {
    
    static let instance = XCReconnectManager()
    
    private let disposeBag = DisposeBag()
    private lazy var bluetoothManager = XCBluetoothManager.instance
    
    public var targetPeripheral: CBPeripheral? // 当前需要监控RSSI的设备
    
    // 退避算法参数
    public var reconnectAttempts = 0
    private let maxReconnectAttempts = 5 // 最大重连次数
    private let baseDelay = 1.0 // 初始延迟时间
    private let maxDelay = 20.0 // 最大延迟时间
    
    // RSSI监控参数
    private var isMonitoringRSSI = false
    private let rssiMonitoringInterval: TimeInterval = 5.0 // 每5秒检查一次RSSI
    private var maxMonitoringDuration: TimeInterval = 60.0 // 最大监控时长，单位为秒
    private var monitoringStartTime: Date? // 记录监控开始时间
    
    private var rssiMonitoringWorkItem: DispatchWorkItem? // 用于取消定时任务
    
    //用户主动自动重连
    func autoReconnectLastPeripheral() -> Observable<ConnectionState> {
        guard let lastModel = bluetoothManager.loadLastConnectedPeripheral(),
              let uuid = lastModel.uuid else {
            return Observable.empty()
        }

        // 尝试直接连接已知外设
        if let lastPeripheral = bluetoothManager.centerManager.retrievePeripherals(withIdentifiers: [uuid]).first {
            return bluetoothManager.connect(to: lastPeripheral)
        }

        // 启动扫描并连接第一个匹配的外设
        bluetoothManager.centerManager.scanForPeripherals(withServices: nil)
        return bluetoothManager.centerManager.rx.didDiscoverPeripheral
            .filter({ $0.0.identifier == uuid })
            .do(onNext: { (periphral,_,_) in
                print("periphral:\(periphral.identifier)")
            })
            .compactMap({ $0.0 })
            .flatMap({ self.bluetoothManager.connect(to:$0) })
    }

    

    
    // 系统自动重连
    func reconnectWithStrategy() {
        if reconnectAttempts < maxReconnectAttempts {
            // 使用指数增加
            let delay = min(baseDelay * pow(2, Double(reconnectAttempts)), maxDelay)
            print("尝试 \(reconnectAttempts + 1)，等待 \(delay) 秒后重连...")
            DispatchQueue.global().asyncAfter(deadline: .now() + delay) { [weak self] in
                
                guard let self = self else { return }
                
                if let peripheral = self.bluetoothManager.connectedPeripheral {
                    self.bluetoothManager.centerManager.connect(peripheral)
                }
            }
            self.reconnectAttempts += 1
        } else {
            startMonitoringRSSI()
        }
    }
    
    // 开始监控RSSI
    func startMonitoringRSSI() {
        guard !isMonitoringRSSI, let peripheral = self.bluetoothManager.connectedPeripheral else { return }
        isMonitoringRSSI = true
        
        monitoringStartTime = Date() // 记录开始时间
        
        print("开始监控设备: \(peripheral.name ?? "未知设备") 的RSSI...")
        monitorRSSI()
    }
    
    // 停止监控RSSI
    func stopMonitoringRSSI() {
        guard isMonitoringRSSI else { return }
        isMonitoringRSSI = false
        
        rssiMonitoringWorkItem?.cancel()
        rssiMonitoringWorkItem = nil
    }
    
    // 监控RSSI
    func monitorRSSI() {
        guard isMonitoringRSSI, let peripheral = self.bluetoothManager.connectedPeripheral else { return }
        
        peripheral.readRSSI()
        
        // 检查是否超过最大监控时长
        if let startTime = monitoringStartTime, Date().timeIntervalSince(startTime) >= maxMonitoringDuration {
            stopMonitoringRSSI() // 超过最大时长，停止监控
            return
        }
        
        rssiMonitoringWorkItem = DispatchWorkItem { [weak self] in
            self?.monitorRSSI()
        }
        
        if let workItem = rssiMonitoringWorkItem {
            DispatchQueue.global().asyncAfter(deadline: .now() + rssiMonitoringInterval, execute: workItem)
        }
    }
    deinit {
        print("XCReconnectManager 已被释放")
    }

}
